import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'dart:io';

/// https://pub.flutter-io.cn/packages/flutter_inappwebview/example
/// https://inappwebview.dev/docs/javascript/communication/

/*
onLoadStop: (controller, url) async {
  await controller.evaluateJavascript(source: """
    window.addEventListener("myCustomEvent", (event) => {
      console.log(JSON.stringify(event.detail));
    }, false);
  """);

  await Future.delayed(Duration(seconds: 5));

  controller.evaluateJavascript(source: """
    window.dispatchEvent(new CustomEvent("myCustomEvent", {
      detail: {foo: 1, bar: false}
    }));
  """);
  await Future.delayed(Duration(seconds: 1));
  controller.evaluateJavascript(source: """
    window.dispatchEvent(new CustomEvent("myCustomEvent", {
      detail: {foo: 1, bar: false}
    }));
  """);
},
onConsoleMessage: (controller, consoleMessage) {
  print(consoleMessage);
  // it will print: {message: {"foo":1,"bar":false}, messageLevel: 1}
},
*/

class HtmlwebApp extends StatefulWidget {
  @override
  _HtmlwebAppState createState() => new _HtmlwebAppState();
}

class _HtmlwebAppState extends State<HtmlwebApp> {
  late InAppWebViewController webView;
  InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
    android: AndroidInAppWebViewOptions(
      useHybridComposition: true,
    ),);

  @override
  void initState() {
    super.initState();
    _init();
  }

  _init() async {
    if (Platform.isAndroid) {
      await AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
          appBar: AppBar(title: Text("Web Message Channels")),
          body: SafeArea(
              child: Column(children: <Widget>[
                Expanded(
                  child: InAppWebView(
                    initialData: InAppWebViewInitialData(
                        data: """
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebMessageChannel Test</title>
</head>
<body>
    <!-- when you click this button, it will send a message to the Dart side -->
    <button id="button" onclick="port.postMessage(input.value);" />Send</button>
    <br />
    <input id="input" type="text" value="JavaScript To Native" />
    <br />
    <br />
    <br />
    <button id="button" onclick="dianji()" />Send</button>
    <br />
    <br />
    <br />
    <button id="button" onclick="toast()" />toast</button>
    <br />
    <span style="margin-top:20px">接收到APP的消息:
            <span id="text"></span>
        </span>
    <br />
    <br />
    
    <script>
      // variable that will represents the port used to communicate with the Dart side
      var port;
      // listen for messages
      window.addEventListener('message', function(event) {
      console.log('收到消息：');
      console.log(event.data);
          if (event.data == 'capturePort') {
              // capture port2 coming from the Dart side
              if (event.ports[0] != null) {
                  // the port is ready for communication,
                  // so you can use port.postMessage(message); wherever you want
                  port = event.ports[0];
                  // To listen to messages coming from the Dart side, set the onmessage event listener
                  port.onmessage = function (event) {
                      // event.data contains the message data coming from the Dart side 
                      console.log(event.data);
                  };
              }
          }
      }, false);
      

function toast(){
console.log('getLoginId');
}

function appSendJs(args){

            console.log(args)
            document.getElementById('text').innerHTML  = args
        }

    </script>
</body>
</html>
"""),
                    initialOptions: options,
                    onWebViewCreated: (controller) async {
                      webView = controller;
                      if (!Platform.isAndroid || await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.WEB_MESSAGE_LISTENER)) {
                        await controller.addWebMessageListener(WebMessageListener(
                          jsObjectName: "myObject",
                          onPostMessage: (message, sourceOrigin, isMainFrame, replyProxy) {
                            // do something about message, sourceOrigin and isMainFrame.
                            replyProxy.postMessage("Got it!");
                          },
                        ));
                      }
                    },
                    onConsoleMessage: (controller, consoleMessage) {
                      print("Message coming from the Dart side: ${consoleMessage.message}");
                      dealConsole(consoleMessage);
                    },
                    onLoadStop: (controller, url) async {
                      if (!Platform.isAndroid || await AndroidWebViewFeature.isFeatureSupported(AndroidWebViewFeature.CREATE_WEB_MESSAGE_CHANNEL)) {
                        // wait until the page is loaded, and then create the Web Message Channel
                        var webMessageChannel = await controller.createWebMessageChannel();
                        var port1 = webMessageChannel!.port1;
                        var port2 = webMessageChannel.port2;

                        // set the web message callback for the port1
                        await port1.setWebMessageCallback((message) async {
                          print("Message coming from the JavaScript side: $message");
                          // when it receives a message from the JavaScript side, respond back with another message.
                          await port1.postMessage(WebMessage(data: message! + " and back"));
                        });

                        // transfer port2 to the webpage to initialize the communication
                        await controller.postWebMessage(message: WebMessage(data: "capturePort", ports: [port2]), targetOrigin: Uri.parse("*"));
                      }
                    },
                  ),
                ),
              ])
          )
      ),
    );
  }

  dealConsole(ConsoleMessage consoleMessage) async {
    if('getLoginId' == consoleMessage.message){
      var result3 =  await webView.evaluateJavascript(source: "appSendJs('hello getLoginId')");
      print(result3);
    }
  }
}